package com.yxp423.ssmempl.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yxp423.ssmempl.bean.Leave;
import com.yxp423.ssmempl.bean.User;
import com.yxp423.ssmempl.mapper.LeaveMapper;
import com.yxp423.ssmempl.service.ILeaveService;
import com.yxp423.ssmempl.service.WebSocketService;
import com.yxp423.ssmempl.utils.base.AjaxResult;
import com.yxp423.ssmempl.utils.consts.ApplyConst;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @Description: java类作用描述
 * @Author: yxp
 * @CreateDate: 2019-05-06 11:27
 * @Version: 1.0
 */
@Service
public class LeaveServiceImpl implements ILeaveService {

	@Autowired
	private LeaveMapper leaveMapper;
	@Autowired
	WebSocketService webSocketService;

	@Override
	public AjaxResult saveLeaveApply(Leave leave) {
		AjaxResult result = new AjaxResult();

		User user = (User) SecurityUtils.getSubject().getPrincipal();

		try {
			leave.setUserId(user.getUserId().toString());
			leave.setCreatTime(DateUtil.date());
			leave.setReviewStatus(ApplyConst.STATUS_CHECKING);
			leaveMapper.insert(leave);
			result.setSuccess(true);
			result.setMsg("添加成功");

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMsg(e.toString());

		}

		return result;
	}

	@Override
	public Page<Leave> myLeave(User user, Page page) {

		leaveMapper.selectPage(
				page,
				new QueryWrapper<Leave>()
						.eq("user_id", user.getUserId())  //拼接SQL字符串 where user_id = ?
						.orderByAsc("review_status")
		);

		return page;
	}

	@Override
	public IPage<Leave> getReviewLeave(Page page, User user) {

		QueryWrapper<Leave> conditions = new QueryWrapper<>();


		leaveMapper.selectPage(
				page,
				conditions
						.eq("reviewer_id", user.getUserId())
						.eq("review_status",ApplyConst.STATUS_CHECKING)
						.orderByDesc("creat_time")

		);

		return page;
	}

	@Override
	public AjaxResult updateLeave(Leave leave) {
		AjaxResult result = new AjaxResult();
		Leave selectById = leaveMapper.selectById(leave.getApplyId());
		if (ObjectUtil.isNull(selectById)) {

			result.setSuccess(false);
			result.setMsg("该申请不存在");
			return result;
		}

		leave.setReviewTime(DateUtil.date());
		int flag = leaveMapper.updateById(leave);
		if (flag > 0) {

			result.setSuccess(true);
			result.setMsg("审核成功,受影响行数" + flag);
			webSocketService.sendToOneUser("您有新的申请被审核",selectById.getUserId());

		} else {

			result.setSuccess(false);
			result.setMsg("审核失败");

		}
		return result;
	}


}
